package com.snow.useviewdemo.function2.hindicon

import android.content.ComponentName
import android.content.Context
import android.content.pm.PackageManager
import android.os.Build
import android.text.TextUtils

/**
 * Created by zhaoyingtao
 * Date: 2021/11/12
 * Describe:
 */
object HindAppIconUtils {
    /**
     * 隐藏桌面图标
     *
     * @param context
     */
    fun dismissAppIcon(context: Context?,defaultFlashActName:String,secondFlashActName:String) {
        //隐藏主图标
        var success = false
        if (!TextUtils.isEmpty(defaultFlashActName) && context != null) {
            val disableComponent = ComponentName(context, defaultFlashActName)
            disableComponent(context, disableComponent)
            success = true
        }
        //Android 10及以上显示副图标
        if (context != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            if (!TextUtils.isEmpty(secondFlashActName)) {
                val component = ComponentName(context, secondFlashActName)
                enableComponent(context, component)
            }
        }
    }

    /**
     * 显示桌面图标
     *
     * @param context
     */
    fun showAppIcon(context: Context?,defaultFlashActName:String) {
        //隐藏主图标
        if (!TextUtils.isEmpty(defaultFlashActName) && context != null) {
            val enableComponent = ComponentName(context, defaultFlashActName)
            enableComponent(context, enableComponent)
        }
    }


    /**
     * 启动组件
     *
     * @param componentName 组件名
     */
    private fun enableComponent(context: Context, componentName: ComponentName) {
        //此方法用以启用和禁用组件，会覆盖Androidmanifest文件下定义的属性
        val mPackageManager = context.packageManager
        mPackageManager.setComponentEnabledSetting(componentName,
                PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                PackageManager.DONT_KILL_APP)
    }


    /**
     * 禁用组件
     *
     * @param componentName 组件名
     */
    private fun disableComponent(context: Context, componentName: ComponentName) {
        val mPackageManager = context.packageManager
        mPackageManager.setComponentEnabledSetting(componentName,
                PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                PackageManager.DONT_KILL_APP)
    }

}